//
//  AppDelegate.swift
//  JMicroBlog
//
//  Created by Jason on 18/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit

// 获取用户的access_token信息
var sharedUserInfo = JAccount.loadUserInfo()

// 切换根视图控制器的通知
let JExchangeRootVCNotification = "JExchangeRootVCNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    // 应用程序加载完成时被调用
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.makeKeyAndVisible()
        
        setAppearance() // 应用程序的整体外观设置
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "exchangeRootVC:", name: JExchangeRootVCNotification, object: nil)
        
        showInterface()
        
        return true
    }
    
    // 主界面的流程
    private func showInterface() {
        var sbName = "JMain"
        // 判断用户是否登录
        if sharedUserInfo != nil {
            // 判断版本是否有更新
            sbName = isNewVerion() ? "JNewFeature" : "JWelcome"
        }
        window?.rootViewController = UIStoryboard.initialViewController(sbName)
    }
    
    // 响应切换主界面的通知事件
    func exchangeRootVC(noti:NSNotification) {
        window?.rootViewController = UIStoryboard.initialViewController(noti.object as! String)
    }
    
    // 是否新更新了版本
    private func isNewVerion() -> Bool{
        // bundle中的版本
        let currentKey = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        // bundle中版本号的数值
        let currentVersion = NSNumberFormatter().numberFromString(currentKey)!.doubleValue
        
        // 和沙盒中的版本进行比较
        let sandboxKey = "sandboxVersion"
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let sandboxVersion = userDefaults.objectForKey(sandboxKey)?.doubleValue
        
        // 即时记录版本号
        userDefaults.setDouble(currentVersion, forKey: sandboxKey)
        
        // 同步,但因为频率不高 其实作用不大
        userDefaults.synchronize()
        
        return currentVersion > sandboxVersion
    }
    
    // MARK: - 整体外观
    func setAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
}

